package com.yueke.gemini.modules.draw;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;

/**
 * 抽奖算法
 * @author qxw
 * @data 2018年8月9日上午10:32:12
 */
public class LotteryTest {

	private static Logger logger = LoggerFactory.getLogger(LotteryTest.class);
	/**
	 * 放大倍数
	 */
	private static final int shakeMulriple = 100000;
	public static List<MdlRoundAboutGift> shakeGiftList = null;
	public static List<String> shakeLzry = null;

	/**
	 * 抽奖逻辑
	 * @param actId  活动id
	 * @param luckyGiftId  默认中奖礼品编号
	 * @return
	 * @throws Exception
	 */
	public static int payShakeGift(String actId,int luckyGiftId) throws Exception {
		int lastScope = 0;
		shakeGiftList = getGiftList(actId);
		if(shakeGiftList==null||shakeGiftList.size()==0){
			return -1;
		}
		//打乱排序 重新洗牌
		Collections.shuffle(shakeGiftList);
		Map<Integer, int[]> giftScopes = new HashMap<Integer, int[]>();
		Map<Integer, Integer> giftQuantity = new HashMap<Integer, Integer>();
		for (MdlRoundAboutGift gift : shakeGiftList) {
			int giftId = gift.getGiftId();
			// 划分区间
			int currentScope = lastScope + gift.getProbability().multiply(new BigDecimal(shakeMulriple)).intValue();
			logger.info("奖品 ID:"+gift.getGiftId()+"奖品"+gift.getGiftName()+"的中奖区间："+lastScope+"~"+ currentScope+"==>奖品剩余数："+gift.getExchangeableCount());
			giftScopes.put(giftId, new int[] { lastScope + 1, currentScope });
			giftQuantity.put(giftId, gift.getExchangeableCount());
			lastScope = currentScope;
		}
		logger.info("lastScope: "+lastScope);
		// 获取1-1000000之间的一个随机数
		int luckyNumber = new Random().nextInt(lastScope);
		logger.info("luckyNumber: "+luckyNumber);
		//默认中奖奖品


		// 查找随机数所在的区间
		if ((null != giftScopes) && !giftScopes.isEmpty()) {
			Set<Entry<Integer, int[]>> entrySets = giftScopes.entrySet();
			for (Entry<Integer, int[]> m : entrySets) {
				int key = m.getKey();
				if (luckyNumber >= m.getValue()[0] && luckyNumber <= m.getValue()[1] && giftQuantity.get(key) > 0) {
					luckyGiftId = key;
					break;
				}
			}
		}
		return luckyGiftId;
	}

	/**
	 * 取出所有奖品
	 */
	public static List<MdlRoundAboutGift> getGiftList(String actId) {
		logger.info("取出数据库活动ID为: "+actId+"  的所有礼品");
		List<MdlRoundAboutGift> list=new ArrayList<MdlRoundAboutGift>();
		list.add(new MdlRoundAboutGift(1, "一等奖",new BigDecimal(0.001), 1, 0, 1,"奖品类型字段"));
		list.add(new MdlRoundAboutGift(2,"二等奖",new BigDecimal(0.002), 1, 0, 1, "奖品类型字段"));
		list.add(new MdlRoundAboutGift(3,"三等奖等奖",new BigDecimal(0.077), 1, 0, 1, "奖品类型字段"));
		return list;
	}

	public static void main(String[] args) throws Exception {
		int giftId=payShakeGift("818", 4);
		logger.info("抽中礼品编号："+giftId);
	}
}
